package win.devhu.testing.javalinweb

import org.slf4j.LoggerFactory
import org.yaml.snakeyaml.Yaml
import java.io.FileInputStream

/** Add a custom profile application.yaml
 * @author Devhu
 */
object Config{

    private val log = LoggerFactory.getLogger(Config::class.java)

    //Get port from config file
    fun getPort(): Int? {
        val config = getYamlProperty()
        var port:Int? = null
        try {
            if(config != emptyMap<String,Any>()) port = Integer.parseInt((config["server"] as MutableMap<String,String>)["port"].toString())
        }catch (e:Exception){
            log.error("application.yaml file format erro\n $e")
        }
        return port
    }

    //Load config file
    private fun getYamlProperty(): Map<String, Any> {
        val yaml = Yaml()
        var config = emptyMap<String,Any>()
//        var ins = this::class.java.classLoader.getResourceAsStream("application.yaml")

        //读取外部配置(即Jar包外文件) --- 外部工程引用该Jar包时需要在工程下创建application.yaml
        val configFile =  System.getProperty("user.dir") + "/application.yaml"
        try {
            val ins = FileInputStream(configFile)
            config = yaml.load<MutableMap<String,Any>>(ins)
            log.info("load configure successful! $config")
        }catch (e:Exception){
            log.info("application.yaml profile not detected using default configuration\n")
            log.error("application.yaml file erro\n $e")
        }

        return config
    }
}
